//
//  MenuTableViewController.m
//  MKUITestApp
//
//  Created by 苏尚进 on 2020/8/24.
//  Copyright © 2020 moon. All rights reserved.
//

#import "MenuTableViewController.h"
#import "MenuTableViewCellModel.h"
#import "MenuListTableViewCellModel.h"
#import "MenuTableViewCell.h"
#import "MenuListTableViewCell2.h"
#import "MenuListTableViewCell_Table.h"
#import "TestUITableViewSectionAdjustsView.h"
@interface MenuTableViewController ()
@property(nonatomic,strong) UIView *toolbarView;
@property(nonatomic,strong) MKUIFlowLayoutButton *selectAllButton;//选中所有
@property(nonatomic,strong) MKUIFlowLayoutButton *deletButton;//删除
@property(nonatomic,strong) MKUIFlowLayoutButton *cancelButton;//取消
@end

@implementation MenuTableViewController
+ (MKTFuncItem *)funcItem{
    return [MKTFuncItem funcWithName:@"菜单列表" viewControllerClass:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 10)];
    headView.backgroundColor = [UIColor redColor];
    headView.layer.borderColor = [UIColor grayColor].CGColor;
    headView.layer.borderWidth = 1;
    self.tableView.tableHeaderView = headView;
    
    self.model.allowsMultipleSelection = YES;
    self.tableView.allowsMultipleSelection = YES;
    //
    UIBarButtonItem *refreshItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(__refresh)];
    UIBarButtonItem *editItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(__edit)];
    self.navigationItem.rightBarButtonItems = @[editItem,refreshItem];
    //
    [self __loadData];
    //
    self.toolbarView = [[UIView alloc] init];
    self.toolbarView.layer.borderWidth = 1;
    self.toolbarView.layer.borderColor = [UIColor grayColor].CGColor;
    self.toolbarView.backgroundColor = [UIColor whiteColor];
    self.selectAllButton = [[MKUIFlowLayoutButton alloc] init];
    [self.selectAllButton setTitle:@"全选" forState:UIControlStateNormal];
    [self.selectAllButton setTitle:@"取消全选" forState:UIControlStateSelected];
    [self.selectAllButton setTitleColor:[UIColor colorWithRed:0 green:0.5 blue:1 alpha:1] forState:UIControlStateNormal];
    [self.selectAllButton addTarget:self action:@selector(__selectAll:) forControlEvents:UIControlEventTouchUpInside];
    [self.toolbarView addSubview:self.selectAllButton];
    
    self.deletButton = [[MKUIFlowLayoutButton alloc] init];
    [self.deletButton setTitle:@"删除" forState:UIControlStateNormal];
    [self.deletButton addTarget:self action:@selector(__deleteSelected:) forControlEvents:UIControlEventTouchUpInside];
    [self.deletButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [self.toolbarView addSubview:self.deletButton];
    
    self.cancelButton = [[MKUIFlowLayoutButton alloc] init];
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancelButton addTarget:self action:@selector(__cancel:) forControlEvents:UIControlEventTouchUpInside];
    [self.cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.toolbarView addSubview:self.cancelButton];
    [self.view addSubview:self.toolbarView];
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewWillLayoutSubviews{
    CGRect oldTableViewFrame = self.tableView.frame;
    [super viewWillLayoutSubviews];
    CGRect bounds = self.safeBounds;
    
    MKUIFillingFlowLayoutConstraint *layout1 = [[MKUIFillingFlowLayoutConstraint alloc] initWithItems:@[self.selectAllButton,self.deletButton,self.cancelButton] constraintParam:(MKUIFillingFlowLayoutConstraint_H_C) contentInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    CGRect f1 = bounds;
    f1.size.height = [layout1 sizeThatFits:f1.size resizeItems:YES].height;
    f1.origin.y = CGRectGetMaxY(bounds)-f1.size.height;
    self.toolbarView.frame = f1;
    {
        CGRect bounds = self.toolbarView.bounds;
        layout1.bounds = bounds;
        [layout1 layoutItemsWithResizeItems:YES];
    }
    self.toolbarView.hidden = !self.model.isEditing;
    UIEdgeInsets contentInset = self.tableView.contentInset;
    if(!self.toolbarView.hidden){
        contentInset.bottom = self.toolbarView.bounds.size.height;
    }
    self.tableView.contentInset = contentInset;
    if(!CGRectEqualToRect(oldTableViewFrame, self.tableView.frame)){
        [self.model reloadTableViewData];
    }
}
- (void)__selectAll:(MKUIFlowLayoutButton *)button{
    button.selected = !button.selected;
    if(button.selected){
        [self.model selectAllCellModelsWithAnimated:YES];
    }else{
        [self.model deselectAllCellModelsWithAnimated:YES];
    }
    [self __updateSelectAllButtonTitle];
    [self.view setNeedsLayout];
}
- (void)__updateSelectAllButtonTitle{
    NSString *title = [NSString stringWithFormat:@"取消全选(%@)",@(self.model.cellModelsForSelectedCellModels.count)];
    [self.selectAllButton setTitle:title forState:UIControlStateSelected];
}
- (void)__deleteSelected:(MKUIFlowLayoutButton *)button{
    [self.model removeCellModels:self.model.cellModelsForSelectedCellModels animated:YES];
    [self __updateSelectAllButtonTitle];
}
- (void)__cancel:(MKUIFlowLayoutButton *)button{
    [self __setEditting:NO];
}
- (void)__refresh{
//    CGFloat h = [self.tableView mk_heightThatFits:self.tableView.bounds.size.width];
    if(self.model.numberOfCells==0){
        [self __loadData];
    }else{
        [self.model reloadTableViewData];
    }
}
- (void)__edit{
    [self __setEditting:!self.model.isEditing];
}
- (void)__loadData{
    [self.model removeAllSectionModels];
    @MK_WEAKIFY(self);
    
    
    
//    MKUITableViewCellSwipeAction *noEditAction = [MKUITableViewCellSwipeAction actionWithStyle:(MKUITableViewCellSwipeActionStyleNormal) title:@"NoEdit" handler:^(MKUITableViewCellSwipeAction * _Nonnull action, MenuTableViewCellModel *cm) {
//        @MK_NORMALIZEANDNOTNIL(self);
//        cm.canEdit = !cm.canEdit;
//    }];
//    MKUITableViewCellSwipeAction *noMoveAction = [MKUITableViewCellSwipeAction actionWithStyle:(MKUITableViewCellSwipeActionStyleNormal) title:@"NoMove" handler:^(MKUITableViewCellSwipeAction * _Nonnull action, MenuTableViewCellModel *cm) {
//        @MK_NORMALIZEANDNOTNIL(self);
//        cm.canMove = !cm.canMove;
//    }];
//    MKUITableViewCellSwipeAction *remoteAction = [MKUITableViewCellSwipeAction actionWithStyle:(MKUITableViewCellSwipeActionStyleNormal) title:@"DelAction" handler:^(MKUITableViewCellSwipeAction * _Nonnull action, MenuTableViewCellModel *cm) {
//        @MK_NORMALIZEANDNOTNIL(self);
//        NSMutableArray<MKUITableViewCellSwipeAction *> *list = [NSMutableArray arrayWithArray:cm.swipeActions];
//        [list removeObjectAtIndex:0];
//        cm.swipeActions = list;
//    }];
    MKUITableViewCellSwipeAction *deleteAction = [MKUITableViewCellSwipeAction actionWithStyle:(MKUITableViewCellSwipeActionStyleDestructive) title:@"删除" handler:^(MKUITableViewCellSwipeAction * _Nonnull action, MenuTableViewCellModel *cm) {
        @MK_NORMALIZEANDNOTNIL(self);
        [cm removeFromModelWithAnimated:YES];
    }];
    MKUITableViewCellSwipeAction *deleteAllAction = [MKUITableViewCellSwipeAction actionWithStyle:(MKUITableViewCellSwipeActionStyleNormal) title:@"删除更多" handler:^(MKUITableViewCellSwipeAction * _Nonnull action, MenuTableViewCellModel *cm) {
        @MK_NORMALIZEANDNOTNIL(self);
        [self __setEditting:YES];
    }];
    NSArray<MKUITableViewCellSwipeAction *> *swipeActions = @[
        deleteAction,
        deleteAllAction,
//        noEditAction,
//        noMoveAction,
//        remoteAction
    ];
    //
    {
        MenuListTableViewCellModel *cm = [[MenuListTableViewCellModel alloc] initWithModelObject:[Menu menuWithIconName:@"app-icon-1.png" title:@"多个View的子菜单" badge:nil]];
        cm.childrenMenus = [[Menu sharedMenus] subarrayWithRange:NSMakeRange(0, 3)];
        [self.model addCellModel:cm];
    }
    {
        MenuListTableViewCellModel *cm = [[MenuListTableViewCellModel alloc] initWithModelObject:[Menu menuWithIconName:@"app-icon-1.png" title:@"Table子菜单" badge:nil]];
//        cm.childrenMenus = [[Menu sharedMenus] subarrayWithRange:NSMakeRange(0, 3)];
        
        cm.childrenMenus = [Menu sharedMenus];
        cm.cellClass = [MenuListTableViewCell_Table class];
        cm.canEdit = YES;
        cm.whenDelete = ^(__kindof MKUITableViewCellModel * _Nonnull cellModel) {
            [cellModel removeFromModelWithAnimated:YES];
        };
        [self.model addCellModel:cm];
    }
    {
        MenuListTableViewCellModel *cm = [[MenuListTableViewCellModel alloc] initWithModelObject:[Menu menuWithIconName:@"app-icon-2.png" title:@"横向Grid" badge:nil]];
        cm.childrenMenus = [[Menu sharedMenus] subarrayWithRange:NSMakeRange(0, 4)];
        cm.cellClass = [MenuListTableViewCell2 class];
        [self.model addCellModel:cm];
    }
    
    {
        MenuListTableViewCellModel *cm = [[MenuListTableViewCellModel alloc] initWithModelObject:[Menu menuWithIconName:@"app-icon-3.png" title:@"竖向Grid" badge:nil]];
        cm.childrenMenus = [Menu sharedMenus];
        cm.cellClass = [MenuListTableViewCell3 class];
        [self.model addCellModel:cm];
    }
    
    {
        MenuListTableViewCellModel *cm = [[MenuListTableViewCellModel alloc] initWithModelObject:[Menu menuWithIconName:@"app-icon-3.png" title:@"竖向GridFix" badge:nil]];
        cm.childrenMenus = [Menu sharedMenus];
        cm.cellClass = [MenuListTableViewCell3_fix class];
        [self.model addCellModel:cm];
    }
    {
        MenuListTableViewCellModel *cm = [[MenuListTableViewCellModel alloc] initWithModelObject:[Menu menuWithIconName:@"app-icon-4.png" title:@"竖向显示一列" badge:nil]];
        cm.childrenMenus = [Menu sharedMenus];
        cm.cellClass = [MenuListTableViewCell4 class];
        [self.model addCellModel:cm];
    }
    {
        MenuListTableViewCellModel *cm = [[MenuListTableViewCellModel alloc] initWithModelObject:[Menu menuWithIconName:@"app-icon-5.png" title:@"横向显示一行" badge:nil]];
        cm.childrenMenus = [Menu sharedMenus];
        cm.cellClass = [MenuListTableViewCell5 class];
        [self.model addCellModel:cm];
    }
    {
        MenuListTableViewCellModel *cm = [[MenuListTableViewCellModel alloc] initWithModelObject:[Menu menuWithIconName:@"app-icon-6.png" title:@"异步加载item" badge:nil]];
        cm.childrenMenus = [Menu sharedUrlMenus];
        cm.cellClass = [MenuListTableViewCell6 class];
        [self.model addCellModel:cm];
    }
    {
        MenuListTableViewCellModel *cm = [[MenuListTableViewCellModel alloc] initWithModelObject:[Menu menuWithIconName:@"app-icon-7.png" title:@"横向显示一行，动态高度" badge:nil]];
        cm.childrenMenus = [Menu sharedMenus];
        cm.cellClass = [MenuListTableViewCell7 class];
        [self.model addCellModel:cm];
    }
    
    {
        MenuListTableViewCellModel *cm = [[MenuListTableViewCellModel alloc] initWithModelObject:[Menu menuWithIconName:@"app-icon-8.png" title:@"横向显示一行（PageFlow）" badge:nil]];
        cm.childrenMenus = [Menu sharedMenus];
        cm.cellClass = [MenuListTableViewCell8 class];
        [self.model addCellModel:cm];
    }
    //
    {
        MKUITableViewSectionModel *sm = [[MKUITableViewSectionModel alloc] init];
        sm.headTitle = @"这是一个非常长的Head！！！这是一个非常长的Head！！！";
        sm.showHeadView = YES;
        sm.headViewClass = [TestUITableViewSectionAdjustsView class];
        sm.footTitle = @"Foot";
        sm.showFootView = YES;
        sm.showDefaultFootView = YES;
        [self.model addSectionModel:sm];
        for (Menu *menu in [Menu sharedMenus]) {
            MenuTableViewCellModel *cm = [[MenuTableViewCellModel alloc] initWithModelObject:menu];
            cm.canEdit = YES;
            cm.canMove = YES;
            cm.whenDelete = ^(MenuTableViewCellModel *cm) {
                [cm.tableViewModel removeCellModel:cm animated:YES];
            };
            cm.whenClick = ^(MenuTableViewCellModel *cm) {
                @MK_NORMALIZE(self);
                if(self.model.isEditing){
                    [self __updateSelectAllButtonTitle];
                }else{
                    cm.canEdit = YES;
                    cm.canMove = YES;
                    cm.swipeActions = swipeActions;
                    cm.selected = NO;
                    [cm deselectCellWithAnimated:YES];
                }
            };
            cm.whenClickAccessory = ^(__kindof MKUITableViewCellModel * _Nonnull cellModel) {
                [cellModel refreshWithAnimated:YES];
            };
            cm.swipeActions = swipeActions;
            cm.performsFirstActionWithFullSwipe = YES;
            [self.model addCellModel:cm];
        }
    }
    
    for (Menu *menu in [Menu sharedUrlMenus]) {
        MenuTableViewCellModel *cm = [[MenuTableViewCellModel alloc] initWithModelObject:menu];
        cm.canEdit = YES;
        cm.canMove = YES;
        cm.whenDelete = ^(MenuTableViewCellModel *cm) {
            [cm.tableViewModel removeCellModel:cm animated:YES];
        };
        cm.whenClick = ^(MenuTableViewCellModel *cm) {
            @MK_NORMALIZE(self);
            if(self.model.isEditing){
                [self __updateSelectAllButtonTitle];
            }else{
                cm.canEdit = YES;
                cm.canMove = YES;
                cm.swipeActions = swipeActions;
                cm.selected = NO;
                [cm deselectCellWithAnimated:YES];
            }
        };
        cm.swipeActions = swipeActions;
        cm.performsFirstActionWithFullSwipe = YES;
        [self.model addCellModel:cm];
    }
    [self.model reloadTableViewData];
}
- (void)__setEditting:(BOOL)editting{
    if(editting){
        [self.tableView setEditing:NO animated:YES];
    }
    self.model.editing = editting;
    [UIView animateWithDuration:0.25 animations:^{
        for (MenuTableViewCell *cell in [self.tableView mk_visibleCellsWithClass:[MenuTableViewCell class]]) {
            [cell setEditting:editting];
        }
    } completion:^(BOOL finished) {
        if(!editting){
            [self.model deselectAllCellModels];
        }
        [self.model reloadTableViewData];
        self.selectAllButton.selected = NO;
        [self __updateSelectAllButtonTitle];
        [self.view setNeedsLayout];
    }];
}

@end
